﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Input;

namespace Twittit.WPF
{
    class LoginViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    

        private void Raise(string propName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }

        public LoginViewModel()
        {

        }

        private String _login;
        public String Login
        {
            get { return _login; }
            set { _login = value; Raise("login"); }
        }

        private String _password;
        public String Password
        {
            get { return _password; }
            set { _password = value; Raise("password"); }
        }

        private String _notice;
        public String Notice
        {
            get { return _notice; }
            set { _notice = value; Raise("notice"); }
        }

        public void LoginClick()
        {
            DoLogin();
        }

        private ICommand _btnLogin;
        public ICommand BtnLogin
        {
            get
            {
                if (_btnLogin == null)
                {
                    this.Notice = "La connexion peut être assez longue. Merci de patienter.";
                    _btnLogin = new RelayCommand(
                        param => this.DoLogin(),
                        param => this.DoCanLogin()
                    );
                }
                return _btnLogin;
            }
        }

        private bool DoCanLogin()
        {
            return true;
        }

        private void DoLogin()
        {
            bool okPass = Twittit.Business.UserService.getInstance().checkPassword(this.Login, this.Password);
            if (okPass)
            {
                this.Notice = "Authentification effectuée, redirection en cours";
                ServiceReferenceUser.ServiceUserClient client = new ServiceReferenceUser.ServiceUserClient();
                //Twittit.DataAccess.User u = client.GetUserByUsername(Login);
                Twittit.DataAccess.User u = Business.UserService.getInstance().getUserByUsername(Login);  
                MainWindow mw = new MainWindow(u);
                mw.Show();
                foreach (System.Windows.Window w in App.Current.Windows)
                {
                    if (w.Name == "Login")
                    {
                        ((Login)w).Notice.Content = "";
                        w.Hide();
                    }
                }
            }
            else
            {
                this.Notice = "Login ou mot de passe incorrect";
            }
        }
    }
}
